//
//  WeAuctionPublishController.m
//  WeGalaxy
//
//  Created by Zheng on 2017/6/30.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "WeAuctionPublishController.h"
#import "TZImagePickerController.h"

#import "WeAuctionPublishContentCell.h"
#import "WeAuctionPublishConditionsCell.h"
#import "WeAuctionPublishBottomView.h"
#import "UWDatePickerView.h"

#import <UIProgressView+AFNetworking.h>



static NSString *const kWeAuctionPublishContentCell_ID = @"kWeAuctionPublishContentCell_ID";
static NSString *const kWeAuctionPublishConditionsCell_ID = @"kWeAuctionPublishConditionsCell_ID";
static CGFloat kBottomHeight = 55;

@interface WeAuctionPublishController () <UWDatePickerViewDelegate>

@property (nonatomic, strong) WeAuctionPublishBottomView *bottomView;
@property (nonatomic, strong) UWDatePickerView *datePicker;
@property (nonatomic) BOOL isBegin;
@property (nonatomic) BOOL isCancel;
@property (nonatomic) CGFloat rowHeight;
@property (nonatomic, copy) NSArray *titlesArr;
@property (nonatomic, copy) NSArray *imagesArr;
@property (nonatomic, strong) NSMutableArray *contentsArr;
@property (nonatomic, strong) NSMutableArray *tasksArr;

@end

@implementation WeAuctionPublishController

#pragma mark - 日期选择
- (void)timePick {
    _datePicker = [UWDatePickerView instanceDatePickerView];
    _datePicker.frame = [UIApplication sharedApplication].keyWindow.bounds;
    _datePicker.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
    _datePicker.delegate = self;
    _datePicker.type = DateTypeOfStart;
    [self.navigationController.view addSubview:_datePicker];
}


- (void)getSelectDate:(NSString *)date type:(DateType)type {
        switch (type) {
        case DateTypeOfStart: {
            NSLog(@"时间 : %@",date);
            NSInteger index = _isBegin? 3:4;
            [_contentsArr replaceObjectAtIndex:index withObject:date];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
            [self.myTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
            break;
            
        case DateTypeOfEnd:
            //TODO:取消
            break;
        default:
            break;
    }
}

#pragma mark - 相册控制器代理
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker
{
    NSLog(@"取消");
}

// 用户选好了图片, 如果assets非空, 则用户选择了原图
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    
    _rowHeight = 280;
    
    _imagesArr = [photos copy];
    
    _rowHeight += (_imagesArr.count/4)*80/375.f*kSCREEN_WIDTH;
    
    [self.myTableView reloadData];

}

#pragma mark - tableview delegate&&datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger rows = (section == 0)? 1: 6;
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        WeAuctionPublishContentCell *cell = [tableView dequeueReusableCellWithIdentifier:kWeAuctionPublishContentCell_ID forIndexPath:indexPath];
        
        __weak typeof(self) weakSelf = self;
        
        cell.addImageBlock = ^{
            kCX_LOG(@"点击了添加图片");
            
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:weakSelf];
            imagePickerVc.allowTakePicture = NO;
            imagePickerVc.allowPickingOriginalPhoto = NO;
            [weakSelf presentViewController:imagePickerVc animated:YES completion:nil];

        };

        
        if (_imagesArr.count != 0) {
            cell.imagesArr = _imagesArr;
        }
        
        cell.tasksBlock = ^(NSURLSessionDataTask *task) {
            if (_isCancel) {
                [task cancel];
            } else {
                [_tasksArr addObject:task];
            }
        };
        
        cell.cancelImageBlock = ^(CGFloat rowHeight) {
            _rowHeight = rowHeight;
            [weakSelf.myTableView reloadData];
        };
        
        return cell;
    } else {
        WeAuctionPublishConditionsCell *cell = [tableView dequeueReusableCellWithIdentifier:kWeAuctionPublishConditionsCell_ID forIndexPath:indexPath];
        
        if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2) {
            cell.contentLbl.hidden = YES;
        } else {
            cell.contentTxf.hidden = YES;
            cell.contentLbl.text = _contentsArr[indexPath.row];
        }
        
        cell.titleLbl.text = _titlesArr[indexPath.row];
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = (indexPath.section == 0)? _rowHeight: 50;
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    CGFloat height = (section == 0)? 0.001: 20;
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        
    if (indexPath.section == 1) {
        [self clickActionWithTag:indexPath.row];
    }
}


#pragma mark - view生命周期

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    _isCancel = YES;
    NSURLSessionDataTask *task = [_tasksArr lastObject];
    [task cancel];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    _isCancel = NO;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"拍卖详情";
    
    _tasksArr = [NSMutableArray new];
    
    _rowHeight = 280;
    
    _titlesArr = @[@"起拍价",@"保证金",@"加价幅度",@"开拍时间",@"结束时间",@"分类"];
    _contentsArr = [@[@"¥ 0",@"¥ 0",@"¥ 0",@"请选择开拍时间",@"请选择结束时间",@"请选择分类"] mutableCopy];

    self.myTableView.backgroundColor = [UIColor whiteColor];
    [self.myTableView registerClass:[WeAuctionPublishContentCell class] forCellReuseIdentifier:kWeAuctionPublishContentCell_ID];
    [self.myTableView registerClass:[WeAuctionPublishConditionsCell class] forCellReuseIdentifier:kWeAuctionPublishConditionsCell_ID];
    CGFloat myTableHeight = kSCREENH_HEIGHT-kBottomHeight-kNAV_BAR_Height-kSTATUS_BAR_Height-10;
    self.myTableView.frame = (CGRect){0,0,kSCREEN_WIDTH,myTableHeight};

    [self.view addSubview:self.bottomView];
    
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.mas_equalTo(kBottomHeight);
    }];
    
    
//    生成纯色图片
//    CGRect rect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
//    UIGraphicsBeginImageContext(rect.size);
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSetFillColorWithColor(context, [[UIColor greenColor] CGColor]);
//    CGContextFillRect(context, rect);
//    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
    
//    UIImage *img = [UIImage imageNamed:@"123.jpeg"];
    
//    [self uploadImageNetworking:img];
}

//- (void)uploadImageNetworking:(UIImage *)image {
//    
//    NSData *data = UIImageJPEGRepresentation(image, 1);
//    
//    NSString *urlStr = @"http://101.200.77.216:8080/kt-app-rest/pic/upload";
//
//    [[AFHTTPSessionManager manager] requestSerializer].timeoutInterval = 60;
//    
//    
//    [[AFHTTPSessionManager manager] POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        NSDateFormatter *formatter = [NSDateFormatter new];
//        formatter.dateFormat = @"yyyyMMddHHmmss";
//        NSString *fileName = [NSString stringWithFormat:@"%@.jpeg", [formatter stringFromDate:[NSDate date]]];
//        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//        [uploadProgress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
// 
//}
//
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//
//    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
//        NSProgress *progress = (NSProgress *)object;
//        NSLog(@"%.0f",100*progress.fractionCompleted);
//        
//    
//    }
//
//}


#pragma mark - 子视图
- (WeAuctionPublishBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[WeAuctionPublishBottomView alloc] init];
        __weak typeof(self) weakSelf = self;
        _bottomView.clickBlock = ^{
            [weakSelf clickActionWithTag:6];
        };
    }
    return _bottomView;
}


#pragma mark - 点击事件
- (void)clickActionWithTag:(NSInteger)tag {
    NSString *title = @"";
    switch (tag) {
        case 3:
            title = @"点击了请选择开拍时间";
            _isBegin = YES;
            [self timePick];
            break;
        case 4:
            title = @"点击了请选择结束时间";
            _isBegin = NO;
            [self timePick];
            break;
        case 5:
            title = @"点击了请选择分类";
            break;
        case 6:
            title = @"点击了确定发布按钮";
            break;
        default:
            break;
    }
    kCX_LOG(@"%@",title);
}


#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
